package com.dpad.telematicsclientapp.ui.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CustomMapStyleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;


import com.amap.api.navi.services.search.model.LatLonPoint;
import com.dpad.telematicsclientapp.Constance;
import com.dpad.telematicsclientapp.android.R;
import com.dpad.telematicsclientapp.mvp.kit.Kits;
import com.dpad.telematicsclientapp.netlibrary.Contances;
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton;
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyFragment;
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.TSFXEntity;
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.TSFXPhone;
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.XTSListEntity;
import com.dpad.telematicsclientapp.presenter.TSFXPresenter;
import com.dpad.telematicsclientapp.util.DataStatisticsUtils;
import com.dpad.telematicsclientapp.util.MyPermissionSet;
import com.dpad.telematicsclientapp.util.TitleToCode;
import com.dpad.telematicsclientapp.util.utils.Constant;
import com.dpad.telematicsclientapp.util.utils.DistanceUtil;
import com.dpad.telematicsclientapp.util.utils.T;
import com.dpad.telematicsclientapp.weight.BasicPPWDialogs;
import com.dpad.telematicsclientapp.weight.DialogPPWUtils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import rx.subscriptions.CompositeSubscription;


public class TSFXFragment extends BaseCopyFragment<TSFXPresenter> implements View.OnClickListener, LocationSource, AMapLocationListener,
        AMap.OnMapClickListener, AMap.OnMarkerClickListener, AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter {

    private View mView;

    private TextureMapView mapView;
    private CoordinatorLayout coordinatorLayout;
    private TextView searchEdt;
    private LinearLayout llJxs;
    private LinearLayout llCdz;
    private LinearLayout llXc;
    private LinearLayout llScj;
    private RelativeLayout rllAczz;
    private TextView tvAczz;
    private LinearLayout llDfbzPhone;
    private LinearLayout bottomSheet;
    private LinearLayout ll_button_right;
    private ImageView img_dingwei_wo;
    private ImageView img_dingwei_cdz;


    private LinearLayout llJtsg;
    private TextView tvName1;
    private TextView tvPhone1;
    private LinearLayout llBjdh;
    private TextView tvName2;
    private TextView tvPhone2;
    private LinearLayout llYlsg;
    private TextView tvName3;
    private TextView tvPhone3;
    private LinearLayout llRbcx;
    private TextView tvName4;
    private TextView tvPhone4;
    private LinearLayout llPabx;
    private TextView tvName5;
    private TextView tvPhone5;
    private LinearLayout llTpybx;
    private TextView tvName6;
    private TextView tvPhone6;
    private GridView gv;
    private LinearLayout ll_phone1, ll_phone2, ll_phone3;


    private BottomSheetBehavior<View> behavior;//滑动控件

    //定位蓝点
    MyLocationStyle myLocationStyle;
    AMap aMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象

    //自己的纬度
    double mylat;
    //自己的经度
    double mylng;
    //自己的位置
    LatLng myLatlng;
    LatLng latLngcar;//车辆的位置
    //武汉市的经纬度
    private LatLng centerWHpoint = new LatLng(30.555178, 114.270637);
    private String city = "";//搜索城市

    private LocationSource.OnLocationChangedListener mListener;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private LatLonPoint latLonPoint;//起点,初次搜索时人的位置，切换城市后为城市中心坐标


    //列表集合  存放所有的点，自动按比例显示在屏幕中
    LatLngBounds.Builder newbounds2;

    List<TSFXEntity.ResultBean.AppMapCollectionBean> beansss = new ArrayList<>();//用来存储收藏的全部数据的

    //旧的标记
    private Marker oldMarker;

    List<TSFXPhone.ResultBean> phoneNumberBeans = new ArrayList<>();//用来记录所有的急救报警等电话号码的

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mView == null) {
            mView = super.onCreateView(inflater, container, savedInstanceState);
        }

        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        requestPermissions();//动态申请权限
        initView();

        if (mapView!=null){

//地图初始化
            mapInit();
            //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
            mapView.onCreate(savedInstanceState);
            Log.i("syssss", "mf onCreateView");
        }


    }



    private void initView() {
        mapView = getView().findViewById(R.id.map_view);
        coordinatorLayout = getView().findViewById(R.id.coordinator);
        searchEdt = getView().findViewById(R.id.search_edt);
        llJxs = getView().findViewById(R.id.ll_jxs);
        llCdz = getView().findViewById(R.id.ll_cdz);
        llXc = getView().findViewById(R.id.ll_xc);
        llScj = getView().findViewById(R.id.ll_scj);
        rllAczz = getView().findViewById(R.id.rll_aczz);
        tvAczz = getView().findViewById(R.id.tv_aczz);
        llDfbzPhone = getView().findViewById(R.id.ll_dfbz_phone);

        bottomSheet = getView().findViewById(R.id.bottom_sheet);
        ll_button_right = getView().findViewById(R.id.ll_button_right);
        img_dingwei_wo = getView().findViewById(R.id.img_dingwei_wo);
        img_dingwei_cdz = getView().findViewById(R.id.img_dingwei_cdz);
        llJtsg = getView().findViewById(R.id.ll_jtsg);
        tvName1 = getView().findViewById(R.id.tv_name1);
        tvPhone1 = getView().findViewById(R.id.tv_phone1);
        llBjdh = getView().findViewById(R.id.ll_bjdh);
        tvName2 = getView().findViewById(R.id.tv_name2);
        tvPhone2 = getView().findViewById(R.id.tv_phone2);
        llYlsg = getView().findViewById(R.id.ll_ylsg);
        tvName3 = getView().findViewById(R.id.tv_name3);
        tvPhone3 = getView().findViewById(R.id.tv_phone3);
        llRbcx = getView().findViewById(R.id.ll_rbcx);
        tvName4 = getView().findViewById(R.id.tv_name4);
        tvPhone4 = getView().findViewById(R.id.tv_phone4);
        llPabx = getView().findViewById(R.id.ll_pabx);
        tvName5 = getView().findViewById(R.id.tv_name5);
        tvPhone5 = getView().findViewById(R.id.tv_phone5);
        llTpybx = getView().findViewById(R.id.ll_tpybx);
        tvName6 = getView().findViewById(R.id.tv_name6);
        tvPhone6 = getView().findViewById(R.id.tv_phone6);
        gv = getView().findViewById(R.id.gv);
        ll_phone1 = getView().findViewById(R.id.ll_phone1);
        ll_phone2 = getView().findViewById(R.id.ll_phone2);
        ll_phone3 = getView().findViewById(R.id.ll_phone3);

        searchEdt.setOnClickListener(this);
        llJxs.setOnClickListener(this);
        llCdz.setOnClickListener(this);
        llXc.setOnClickListener(this);
        llScj.setOnClickListener(this);
        rllAczz.setOnClickListener(this);//爱车追踪
        llDfbzPhone.setOnClickListener(this);

        llJtsg.setOnClickListener(this);
        llBjdh.setOnClickListener(this);
        llYlsg.setOnClickListener(this);
        llRbcx.setOnClickListener(this);
        llPabx.setOnClickListener(this);
        llTpybx.setOnClickListener(this);

        img_dingwei_wo.setOnClickListener(this);
        img_dingwei_cdz.setOnClickListener(this);


        ll_button_right.getBackground().setAlpha(35);//设置右上角两个图片背景的透明度

        //底部抽屉栏展示地址
        behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, @BottomSheetBehavior.State int newState) {
                String state = "null";
                switch (newState) {
                    case 1:
                        state = "STATE_DRAGGING";//过渡状态此时用户正在向上或者向下拖动bottom sheet
                        break;
                    case 2:
                        state = "STATE_SETTLING"; // 视图从脱离手指自由滑动到最终停下的这一小段时间
                        break;
                    case 3:
                        state = "STATE_EXPANDED"; //处于完全展开的状态

                        break;
                    case 4:
                        state = "STATE_COLLAPSED"; //默认的折叠状态

                        break;
                    case 5:
                        state = "STATE_HIDDEN"; //下滑动完全隐藏 bottom sheet
//                        behavior.setPeekHeight(UIUtils.dip2px(300));

//                        T.showToastSafeError("到了最下面了");
//                        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                        behavior.setHideable(false);//不让隐藏

                        break;
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
//                Log.d("BottomSheetDemo", "slideOffset:" + slideOffset);
            }
        });


        gv.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return phoneNumberBeans == null ? 0 : phoneNumberBeans.size();
            }

            @Override
            public Object getItem(int position) {
                return phoneNumberBeans.get(position) == null ? "" : phoneNumberBeans.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view;
                Holder holder;
                if (convertView == null) {
                    view = View.inflate(getContext(), R.layout.item_gv_tsfx_phone, null);
                    holder = new Holder();
                    holder.ll_call_phone = view.findViewById(R.id.ll_call_phone);
                    holder.tv_call_name = view.findViewById(R.id.tv_call_name);
                    holder.tv_call_phone = view.findViewById(R.id.tv_call_phone);


                    holder.tv_call_name.setText(phoneNumberBeans.get(position).getCodeName() == null ? "" : phoneNumberBeans.get(position).getCodeName());
                    holder.tv_call_phone.setText(phoneNumberBeans.get(position).getCodeValue() == null ? "" : phoneNumberBeans.get(position).getCodeValue());


                    holder.ll_call_phone.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String s = phoneNumberBeans.get(position).getCodeValue();
                            DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：" + s, Constant.NOMAL));
                            Intent intent2 = new Intent(Intent.ACTION_DIAL);
                            Uri data2 = Uri.parse("tel:" + phoneNumberBeans.get(position).getCodeValue());
                            intent2.setData(data2);
                            startActivity(intent2);
                        }
                    });


                    view.setTag(holder);
                } else {
                    view = convertView;
                    holder = (Holder) view.getTag();
                }


                return view;

            }
        });



    }

    class Holder {
        LinearLayout ll_call_phone;
        TextView tv_call_name;
        TextView tv_call_phone;

    }


    //地图初始化
    private void mapInit() {
        aMap = mapView.getMap();
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(centerWHpoint, 14));
        if (aMap != null) {
            //设置显示定位按钮 并且可以点击
            UiSettings settings = aMap.getUiSettings();
            aMap.setLocationSource(this);//设置了定位的监听,这里要实现LocationSource接口
            // 是否显示定位按钮
            settings.setMyLocationButtonEnabled(false);

            //设置地图的放缩级别
            aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
            // 设置定位监听
            aMap.setLocationSource(this);
            // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase
        }

        //设置自定义地图的方法
        zhuti();
        //蓝点初始化
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。

        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.mylocation));// 设置小蓝点的图标

        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        //myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）默认执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//只定位一次
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE) ;//定位一次，且将视角移动到地图中心点。
        myLocationStyle.showMyLocation(true);

        //隐藏定位范围的圈圈
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style

        aMap.setOnMapClickListener(this);
        aMap.setOnMarkerClickListener(this);

        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);//隐藏放大缩小按钮
        mUiSettings.setZoomGesturesEnabled(true);//启用缩放手势


        if (MainApplicaton.sIsLogin) {//登录了再请求收藏列表
            getP().getCollection();//探索发现首页获取收藏点的接口
        }

        getP().getPhone();//获取首页电话

    }

    @Override
    protected void initPageData() {

    }

    //每次切换的时候会调用
    @Override
    public void visiableLoadData() {
//        super.visiableLoadData();
//            userVehType字段//用户和车辆类型（0：游客1:电动T车2：混动T车3：燃油T车4：非T车）
        if (MainApplicaton.getUserVehType().equals("1") || MainApplicaton.getUserVehType().equals("2") || MainApplicaton.getUserVehType().equals("3")) {//当前是T车的时候，才显示寻车和爱车追踪

            Log.e("syssss", MainApplicaton.getUserVehType() + "证明是T车主");


            if (MainApplicaton.sIsLogin) {
                llXc.setVisibility(View.VISIBLE);
                rllAczz.setVisibility(View.VISIBLE);
//                Log.e("syssss","登录了");

                if (MainApplicaton.getUserVehType().equals("3")) {//如果登录的情况下，是燃油T车，此时不显示充电桩
                    llCdz.setVisibility(View.GONE);
                } else {
                    llCdz.setVisibility(View.VISIBLE);//充电桩按钮
                }

            } else {
                llXc.setVisibility(View.GONE);
                rllAczz.setVisibility(View.GONE);
//                Log.e("syssss","没有登录");
                llCdz.setVisibility(View.VISIBLE);//充电桩按钮
            }



            if (aMap != null) {
                aMap.clear();
            }

            mapInit();


//            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) coordinatorLayout.getLayoutParams(); //取控件textView当前的布局参数
//            linearParams.height = ScreenUtil.dip2px(getContext(), 450);// 控件的高强制设成450
//
//            coordinatorLayout.setLayoutParams(linearParams); //使设置好的布局参数应用到控件

        } else {//否则，没有登录和不是T车，就不显示寻车和爱车追踪

            Log.e("syssss", "证明是没登录，或者是游客，非T车");

            llCdz.setVisibility(View.VISIBLE);//充电桩按钮
            llXc.setVisibility(View.GONE);//寻车按钮
            rllAczz.setVisibility(View.GONE);

            if (aMap != null) {
                aMap.clear();
            }
            mapInit();

        }

        getP().getxiaotieshi();//判断充电桩按钮是否显示的


    }
//    @Override
//    public void onHiddenChanged(boolean hidden) {//根据hidden判断，当前是否重新回来这个fragment，切换fragment的时候会调用
//        super.onHiddenChanged(hidden);
//        if (hidden) {
//            return;
//        } else {
//            //从其他界面返回到此界面的时候
////            Log.e(TAG, "onDetach: ddddddd333eee" );
//
//
//        }
//
//    }


    //充电桩按钮是否显示返回的结果
    public void chongdianzhuang(XTSListEntity bean){
        Log.e("接口调用", "已返回");
        if (!Kits.Empty.check(bean)){
            if (bean.getCode().equals("00000")){

                if (bean.getResult().size()>0){
                    if (!Kits.Empty.check(bean.getResult().get(0).getCodeValue())){
                        if (bean.getResult().get(0).getCodeValue().equals("0")){//1显示充电桩按钮，0不显示
                            llCdz.setVisibility(View.GONE);//充电桩按钮
                        }else {
                            llCdz.setVisibility(View.VISIBLE);//充电桩按钮
                        }
                    }
                }



            }

        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_tsfx;
    }

    @Override
    protected TSFXPresenter newPresenter(CompositeSubscription subscriptions) {
        return new TSFXPresenter();
    }

    @Override
    public void onClick(View v) {
        MainApplicaton.pageType = 0;
        switch (v.getId()) {
            case R.id.img_dingwei_cdz://左上角的充电的按钮
                break;
            case R.id.img_dingwei_wo://定位自己的按钮

                if (aMap != null) {
                    aMap.clear();
                }
                mapInit();
                break;

            case R.id.search_edt://搜索
// //                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE119.getTitle(), System.currentTimeMillis() + "", Constant.NOMAL));
//                Intent intentss = new Intent(getContext(), TSearchMapActivity.class);
//                intentss.putExtra("city", city);
//                startActivityForResult(intentss, 1223);

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_TSEARCH,Contances.GROUP_HOME)
                        .withString("city",city)
                        .navigation(context,1223);



                break;
            case R.id.ll_jxs://经销商
// //             DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE116.getTitle(), System.currentTimeMillis() + "", Constant.NOMAL));
//                Intent intent9 = new Intent(getContext(), JXSActivity.class);
//                intent9.putExtra("tag","1");
//                startActivity(intent9);


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_JXS,Contances.GROUP_HOME)
                        .withString("tag","1")
                        .navigation(context);

                break;
            case R.id.ll_cdz://充电桩
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE81.getTitle(), System.currentTimeMillis() + "", Constant.NOMAL));
                Intent intents = new Intent();
                intents.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("https://qr.alipay.com/s6x04082xwqdvjzamu795ad");
                intents.setData(content_url);
                startActivity(intents);

                break;
            case R.id.ll_xc://寻车
//                Intent intent10 = new Intent(getContext(), XunCheActivity.class);
//                startActivityForResult(intent10, 107);


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_XUNCHE,Contances.GROUP_HOME)
                        .navigation(context,107);


                break;
            case R.id.ll_scj://收藏夹
//                Intent intent8 = new Intent(getContext(), ShouCangActivity.class);
//                intent8.putExtra("lat", mylat);
//                intent8.putExtra("lng", mylng);
//                intent8.putExtra("city", city);
//                startActivityForResult(intent8, 1228);


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_SHOUCANG,Contances.GROUP_HOME)
                        .withDouble("lat", mylat)
                        .withDouble("lng", mylng)
                        .withString("city",city)
                        .navigation(context,1228);


                break;
            case R.id.rll_aczz://爱车追踪
                MainApplicaton.pageType = 0;
//                Intent intent7 = new Intent(getContext(), DczzActivity.class);
//                startActivity(intent7);

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_DCZZ,Contances.GROUP_DAOCHE)
                        .navigation(context);



                break;
            case R.id.ll_dfbz_phone://东风标致
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：4008877108", Constant.NOMAL));
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + "4008877108");
                intent.setData(data);
                startActivity(intent);
                break;
            case R.id.ll_jtsg://交通事故
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：122", Constant.NOMAL));
                Intent intent1 = new Intent(Intent.ACTION_DIAL);
                Uri data1 = Uri.parse("tel:" + "122");
                intent1.setData(data1);
                startActivity(intent1);
                break;
            case R.id.ll_bjdh://报警电话
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：110", Constant.NOMAL));
                Intent intent2 = new Intent(Intent.ACTION_DIAL);
                Uri data2 = Uri.parse("tel:" + "110");
                intent2.setData(data2);
                startActivity(intent2);
                break;
            case R.id.ll_ylsg://医疗事故
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：120", Constant.NOMAL));
                Intent intent3 = new Intent(Intent.ACTION_DIAL);
                Uri data3 = Uri.parse("tel:" + "120");
                intent3.setData(data3);
                startActivity(intent3);
                break;
            case R.id.ll_rbcx://人保财险
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：95518", Constant.NOMAL));
                Intent intent4 = new Intent(Intent.ACTION_DIAL);
                Uri data4 = Uri.parse("tel:" + "95518");
                intent4.setData(data4);
                startActivity(intent4);
                break;
            case R.id.ll_pabx://平安保险
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：95511", Constant.NOMAL));
                Intent intent5 = new Intent(Intent.ACTION_DIAL);
                Uri data5 = Uri.parse("tel:" + "95511");
                intent5.setData(data5);
                startActivity(intent5);
                break;
            case R.id.ll_tpybx://太平洋保险
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE118.getTitle(), System.currentTimeMillis() + "", "拨打电话：95500", Constant.NOMAL));
                Intent intent6 = new Intent(Intent.ACTION_DIAL);
                Uri data6 = Uri.parse("tel:" + "95500");
                intent6.setData(data6);
                startActivity(intent6);
                break;


        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        //解析AMapLocation对象
        //首先，可以判断AMapLocation对象不为空，当定位错误码类型为0时定位成功。
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点

                //可在其中解析amapLocation获取相应内容。
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                String address = amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                String country = amapLocation.getCountry();//国家信息
                amapLocation.getProvince();//省信息
                amapLocation.getCity();//城市信息
                amapLocation.getDistrict();//城区信息
                amapLocation.getStreet();//街道信息
                amapLocation.getStreetNum();//街道门牌号信息
                amapLocation.getCityCode();//城市编码
                amapLocation.getAdCode();//地区编码
                amapLocation.getAoiName();//获取当前定位点的AOI信息
                amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
                amapLocation.getFloor();//获取当前室内定位的楼层
                //amapLocation.getGpsStatus();//获取GPS的当前状态
                amapLocation.getGpsAccuracyStatus();
                //获取定位时间
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                String format = df.format(date);

                Log.e("qqqq", "地址:" + address + "----国家信息:" + country + "----time--> " + format);
//                imgLayerHead.setVisibility(View.VISIBLE);//显示定位图标


                city = amapLocation.getCity();
                mylat = amapLocation.getLatitude();//自己的纬度
                mylng = amapLocation.getLongitude();//自己的经度

                myLatlng = new LatLng(mylat, mylng);

                centerWHpoint = new LatLng(mylat, mylng);//设置地图默认中心点

                latLonPoint = new LatLonPoint(mylat, mylng);//默认为人的位置，搜索周边，切换城市后变成城市中心坐标
                MainApplicaton.getInstance().setLatLonPoint(latLonPoint);
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(myLatlng));


                //            userVehType字段//用户和车辆类型（0：游客1:电动T车2：混动T车3：燃油T车4：非T车）
//                if (MainApplicaton.getUserVehType().equals("1") ||MainApplicaton.getUserVehType().equals("2") ||MainApplicaton.getUserVehType().equals("3")) {//当前是T车的时候，才显示寻车和爱车追踪
//
//                    llXc.setVisibility(View.VISIBLE);
//                    rllAczz.setVisibility(View.VISIBLE);
//
//
//                } else {//否则，没有登录和不是T车，就不显示寻车和爱车追踪
//
//                    llXc.setVisibility(View.GONE);
//                    rllAczz.setVisibility(View.GONE);
//
//
//                }


            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("qqqq", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    private void init() {

        //初始化定位
        mLocationClient = new AMapLocationClient(MainApplicaton.getInstance().getApplicationContext());

        //设置定位回调监听
        mLocationClient.setLocationListener(this);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();


        //--------------------------------------------------
        //选择定位场景

        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        //mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);

       /* if(null != mLocationClient){
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }*/

        //--------------------------------------------------
        //选择定位模式

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);


        //设置单次定位

        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);

        //--------------------------------------------------
        //自定义连续定位

        //SDK默认采用连续定位模式，时间间隔2000ms。如果您需要自定义调用间隔：
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);

        //--------------------------------------------------
        //其他参数
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //设置是否允许模拟软件Mock位置结果，多为模拟GPS定位结果，默认为true，允许模拟位置。
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(true);

        //设置定位请求超时时间，默认为30秒。
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(8000);

        //设置是否开启定位缓存机制
        //缓存机制默认开启，可以通过以下接口进行关闭。
        //当开启定位缓存功能，在高精度模式和低功耗模式下进行的网络定位结果均会生成本地缓存，不区分单次定位还是连续定位。GPS定位结果不会被缓存。
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);

        //--------------------------------------------------
        //启动定位
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

        //停止定位
        //mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁

        //销毁定位客户端
        //销毁定位客户端之后，若要重新开启定位请重新New一个AMapLocationClient对象。
        //mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。

        //注意事项
        //目前手机设备在长时间黑屏或锁屏时CPU会休眠，这导致定位SDK不能正常进行位置更新。
        //若您有锁屏状态下获取位置的需求，您可以应用alarmManager实现1个可叫醒CPU的Timer，定时请求定位。
        //使用定位SDK务必要注册GPS和网络的使用权限。
        //在使用定位SDK时，请尽量保证网络畅通，如获取网络定位，地址信息等都需要设备可以正常接入网络。
        // 定位SDK在国内返回高德类型坐标，海外定位将返回GPS坐标。
    }


    //设置自定义地图样式的方法
    private void zhuti() {
        byte[] buffer1 = null;
        byte[] buffer2 = null;
        InputStream is1 = null;
        InputStream is2 = null;
        try {
            is1 = getContext().getAssets().open("style.data");
            int lenght1 = is1.available();
            buffer1 = new byte[lenght1];
            is1.read(buffer1);
            is2 = getContext().getAssets().open("style_extra.data");
            int lenght2 = is2.available();
            buffer2 = new byte[lenght2];
            is2.read(buffer2);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is1 != null)
                    is1.close();
                if (is2 != null)
                    is2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        CustomMapStyleOptions customMapStyleOptions = new CustomMapStyleOptions();
        customMapStyleOptions.setStyleData(buffer1);
        customMapStyleOptions.setStyleExtraData(buffer2);
        aMap.setCustomMapStyle(customMapStyleOptions);
    }


    @Override
    public View getInfoWindow(Marker marker) {

        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (oldMarker != null) {
            oldMarker.hideInfoWindow();
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {

        if (!marker.getPosition().equals(myLatlng)) { //点击的marker不是自己位置的那个marker,图标才能变大
            if (oldMarker != null) {
//                oldMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.maplittleother));
                oldMarker.hideInfoWindow();
            }
            oldMarker = marker;


            int snippet = Integer.parseInt(marker.getSnippet());//知道了是第几个

//            String dists=snippet.substring(0,snippet.indexOf("address"));//距离
//            String adds=snippet.substring(snippet.indexOf("address")+7,snippet.indexOf("poiid"));//地址
//            String poiids=snippet.substring(snippet.indexOf("poiid")+5,snippet.indexOf("lat"));//poiId
//            String lats=snippet.substring(snippet.indexOf("lat")+3,snippet.indexOf("lng"));//纬度
//            String lngs=snippet.substring(snippet.indexOf("lng")+3,snippet.indexOf("poiCategory"));//经度
//            String poiCategorys=snippet.substring(snippet.indexOf("poiCategory")+11,snippet.indexOf("id"));//分类编码
//            String ids=snippet.substring(snippet.indexOf("id")+2,snippet.indexOf("phone"));//id  用来取消收藏的
//            String phones=snippet.substring(snippet.indexOf("phone")+5);


            String ss = beansss.get(snippet).getPoiCoordinate();
            String latmarks = ss.substring(0, ss.indexOf(","));
            String lngmarks = ss.substring(ss.indexOf(",") + 1);

            double latsss = Double.parseDouble(latmarks);
            double lngsss = Double.parseDouble(lngmarks);

            LatLng latLng = new LatLng(latsss, lngsss);


            float distance = AMapUtils.calculateLineDistance(myLatlng, latLng);


            String dists = DistanceUtil.formateDistance(distance);//距离
            String adds = beansss.get(snippet).getPoiAddress() == null ? "" : beansss.get(snippet).getPoiAddress();//地址
            String poiids = beansss.get(snippet).getPoiId() == null ? "" : beansss.get(snippet).getPoiId();//poiId
            String lats = latmarks;//纬度
            String lngs = lngmarks;//经度
            String poiCategorys = beansss.get(snippet).getPoiCategory() == null ? "" : beansss.get(snippet).getPoiCategory();//分类编码
            String ids = beansss.get(snippet).getId() == null ? "" : beansss.get(snippet).getId();//id  用来取消收藏的
            String phones = beansss.get(snippet).getPhone() == null ? "" : beansss.get(snippet).getPhone();
            String appointFlag=beansss.get(snippet).getAppointFlag() == null ? "" : beansss.get(snippet).getAppointFlag();
            String resucePhone=beansss.get(snippet).getResucePhone()==null?"":beansss.get(snippet).getResucePhone();//爱心救援电话
            String siteno=beansss.get(snippet).getSiteNo()==null?"":beansss.get(snippet).getSiteNo();

            if (poiCategorys.equals("4")) {//如果是经销商，则跳转到经销商页面
//                Intent intent = new Intent(getContext(), ShouCangJXSDetailActivity.class);
//                intent.putExtra("sitename", marker.getTitle());
//                intent.putExtra("distance", dists);
//                intent.putExtra("address", adds);//地址
//                intent.putExtra("phone", phones);
//                intent.putExtra("lat", lats);
//                intent.putExtra("lng", lngs);
//                intent.putExtra("poiid", poiids);
//                intent.putExtra("id", ids);//用来取消收藏的
//                intent.putExtra("appointFlag",appointFlag);//是否可以预约
//                intent.putExtra("resucePhone",resucePhone);
//                intent.putExtra("siteNo",siteno);
//                startActivityForResult(intent, 109);


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_SHOUCANG_JXSDETAIL,Contances.GROUP_HOME)
                        .withString("sitename", marker.getTitle())
                        .withString("distance", dists)
                        .withString("address", adds)
                        .withString("phone", phones)
                        .withString("lat",lats)
                        .withString("lng",lngs)
                        .withString("poiid", poiids)
                        .withString("id",ids)//用来取消收藏的
                        .withString("appointFlag",appointFlag)//是否可以预约
                        .withString("resucePhone",resucePhone)
                        .withString("siteNo",siteno)
                        .navigation(context,109);




            } else {
//                Intent intent = new Intent(getContext(), ShouCangSearchDetailActivity.class);
//                intent.putExtra("sitename", marker.getTitle());
//                intent.putExtra("distance", dists);
//                intent.putExtra("address", adds);//地址
//                intent.putExtra("phone", phones);
//                intent.putExtra("lat", lats);
//                intent.putExtra("lng", lngs);
//                intent.putExtra("poiid", poiids);
//                intent.putExtra("id", ids);//用来取消收藏的
//                intent.putExtra("poiCategory","3");//1 家,2公司,3一般,4经销商
//                startActivityForResult(intent, 109);


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_SHOUCANG_SEARCHDETAIL,Contances.GROUP_HOME)
                        .withString("sitename", marker.getTitle())
                        .withString("distance", dists)
                        .withString("address", adds)
                        .withString("phone", phones)
                        .withString("lat",lats)
                        .withString("lng",lngs)
                        .withString("poiid", poiids)
                        .withString("id",ids)//用来取消收藏的
                        .withString("poiCategory","3")//1 家,2公司,3一般,4经销商
                        .navigation(context,109);



            }


        } else {//如果是自己的Marker

        }


        return false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        Log.i("syssss", "mf onResume");
        super.onResume();
        mapView.onResume();
        visiableLoadData();//当界面可见的时候判断身份
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onPause() {
        Log.i("syssss", "mf onPause");
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i("syssss", "mf onSaveInstanceState");
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onDestroy() {
        Log.i("syssss", "mf onDestroy");
        super.onDestroy();
        mapView.onDestroy();
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        //初始化定位
        init();
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    //动态申请权限
    private void requestPermissions() {

        List<String> permissionList = new ArrayList<>();
//        允许程序打开网络套接字
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.INTERNET);
        }
//        允许程序设置内置sd卡的写权限
//        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//        }
//        允许程序获取网络状态
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_NETWORK_STATE);
        }
//                允许程序访问WiFi网络信息
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_WIFI_STATE);
        }
//        允许程序读写手机状态和身份
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//            permissionList.add(Manifest.permission.READ_PHONE_STATE);
//        }
//                允许程序访问CellID或WiFi热点来获取粗略的位置
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        //申请打电话权限
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//            permissionList.add(Manifest.permission.CALL_PHONE);
//        }

        if (!permissionList.isEmpty()) {  //申请的集合不为空时，表示有需要申请的权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(permissionList.toArray(new String[permissionList.size()]), 1);
            }
        } else { //所有的权限都已经授权过了


            //判断用户是否拒绝了定位权限
            if (isLocationEnabled()){//如果打开了，不做处理

            }else {
                T.showToastSafeError("请打开系统GPS开关再操作");
//                dontDingWei();
            }

        }
    }

    //动态申请权限部分
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) { //安全写法，如果小于0，肯定会出错了
                    for (int i = 0; i < grantResults.length; i++) {

                        int grantResult = grantResults[i];
                        if (grantResult == PackageManager.PERMISSION_DENIED) { //这个是权限拒绝
                            String s = permissions[i];
//                            Toast.makeText(this, s + "权限被拒绝了", Toast.LENGTH_SHORT).show();
//                            T.showToastSafeError("暂未获取到定位信息");


                            //判断用户是否拒绝了定位权限
                            PackageManager pm = getContext().getPackageManager();
                            boolean flag = (PackageManager.PERMISSION_GRANTED ==
                                    pm.checkPermission("android.permission.ACCESS_COARSE_LOCATION", "packageName"));

                            if (flag) {
                                //有这个权限，做相应处理
                            } else { //没有权限

                                //如果勾选了"以后不再提示"
//                                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.ACCESS_COARSE_LOCATION)==false){



                                DialogPPWUtils.showBasicDialogs(getActivity(), "提示", "东风标致智行需要开启定位权限才能正常使用",
                                        "取消", "去设置", (dialog, confirm) -> {
                                            if (confirm) {//点击去设置跳转到系统设置打开定位权限的页面
                                                String sdk = Build.VERSION.SDK; // SDK号

                                                String model = Build.MODEL; // 手机型号

                                                String release = Build.VERSION.RELEASE; // android系统版本号
                                                String brand = Build.BRAND;//手机厂商
                                                if (TextUtils.equals(brand.toLowerCase(), "redmi") || TextUtils.equals(brand.toLowerCase(), "xiaomi")) {
                                                    MyPermissionSet.gotoMiuiPermission(getActivity());//小米
                                                } else if (TextUtils.equals(brand.toLowerCase(), "meizu")) {
                                                    MyPermissionSet.gotoMeizuPermission(getActivity());
                                                } else if (TextUtils.equals(brand.toLowerCase(), "huawei") || TextUtils.equals(brand.toLowerCase(), "honor")) {
                                                    MyPermissionSet.gotoHuaweiPermission(getActivity());
                                                } else {
                                                    startActivity(MyPermissionSet.getAppDetailSettingIntent());
                                                }

                                                dialog.dismiss();//关闭弹窗
//                                                setResult(0506);
//                                                Czdh3Activity.this.finish();//高德地图中跳转到设置页面以后，关闭了当前页面，这里也关闭

                                            } else {
//                                                dontDingWei();//点击了取消提示框的操作
                                            }
//                                                dialog.dismiss();
                                        });

//                                }else {
//                                    dontDingWei();//当直接拒绝以后
//                                }

                            }


                        } else { //授权成功了
                            //do Something
                            mapInit();

                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1228 && resultCode == Constant.T_MAP_COLLECTION_RESULTCODE) {//收藏返回

            if (MainApplicaton.sIsLogin) {
                aMap.clear();
                mapInit();
//                getP().getCollection();//重新请求标记点
            }


        } else if (requestCode == 1223 && resultCode == 1011) {//搜索返回
            if (MainApplicaton.sIsLogin) {
                aMap.clear();
                mapInit();
//                getP().getCollection();//重新请求标记点
            }


        } else if (requestCode == 107 && resultCode == 107) {//寻车返回
            if (MainApplicaton.sIsLogin) {
                aMap.clear();
                mapInit();
//                getP().getCollection();//重新请求标记点
            }

        } else if (requestCode == 109 && resultCode == 109) {//点击Marker跳转返回
            if (MainApplicaton.sIsLogin) {
                aMap.clear();
                mapInit();
//                getP().getCollection();//重新请求标记点
            }
        }
    }

    //查询所有的收藏点，展示在页面上
    public void showListSC(List<TSFXEntity.ResultBean.AppMapCollectionBean> beans, TSFXEntity.ResultBean.VehLocationVoBean voBean) {

        if (!(beans == null || beans.equals(""))) {


            beansss.clear();
            beansss.addAll(beans);//添加到里面，设置成全局


            for (int j = 0; j < beans.size(); j++) {
                String ss = beans.get(j).getPoiCoordinate();
                String latss = ss.substring(0, ss.indexOf(","));
                String lngss = ss.substring(ss.indexOf(",") + 1);

                double latsss = Double.parseDouble(latss);
                double lngsss = Double.parseDouble(lngss);

                LatLng latLng = new LatLng(latsss, lngsss);

                float distance = AMapUtils.calculateLineDistance(myLatlng, latLng);

                String distancess = DistanceUtil.formateDistance(distance);//距离


                if (beans.get(j).getPoiCategory().equals("4")) {//1 家,2公司,3一般,4经销商
                    aMap.addMarker(new MarkerOptions()
                            .position(latLng)
                            .title(beans.get(j).getPoiName())
                            .snippet(j + "")
                            .icon(BitmapDescriptorFactory
                                    .fromResource(R.mipmap.img_tsfx_sc_jxs))
                            .draggable(true));
                } else {
                    aMap.addMarker(new MarkerOptions()
                            .position(latLng)
                            .title(beans.get(j).getPoiName())
                            .snippet(j + "")
                            .icon(BitmapDescriptorFactory
                                    .fromResource(R.mipmap.img_tsfx_sc_other))
                            .draggable(true));
                }


            }


        }


        newbounds2 = new LatLngBounds.Builder();

        if (!(voBean == null || voBean.equals(""))) {

            if (!(voBean.getPosition().getLatitude() == null || voBean.getPosition().getLatitude().equals("")
                    || voBean.getPosition().getLongitude() == null || voBean.getPosition().getLongitude().equals(""))) {
                double latcar = Double.parseDouble(voBean.getPosition().getLatitude());
                double lngcar = Double.parseDouble(voBean.getPosition().getLongitude());

                latLngcar = new LatLng(latcar, lngcar);

                if (voBean.getPosition().getAddress() != null) {
                    aMap.addMarker(new MarkerOptions()
                            .position(latLngcar)
                            .title(voBean.getPosition().getAddress())
                            .icon(BitmapDescriptorFactory
                                    .fromResource(R.mipmap.img_car_location))
                            .draggable(true));
                }

                newbounds2.include(latLngcar);
            }


            newbounds2.include(myLatlng);

            //所有的点都展示在地图上
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(newbounds2.build(), 220));//第二个参数为四周留空宽度
        }


    }


    //查询电话号码设置上去
    public void showPhoneNumber(List<TSFXPhone.ResultBean> phoneBeans) {

        if (!Kits.Empty.check(phoneBeans)) {
            if (phoneBeans.size() > 0) {
                phoneNumberBeans.clear();
                phoneNumberBeans.addAll(phoneBeans);

                gv.setVisibility(View.VISIBLE);
                ll_phone1.setVisibility(View.GONE);
                ll_phone2.setVisibility(View.GONE);
                ll_phone3.setVisibility(View.GONE);
            } else {
                gv.setVisibility(View.GONE);
                ll_phone1.setVisibility(View.VISIBLE);
                ll_phone2.setVisibility(View.VISIBLE);
                ll_phone3.setVisibility(View.VISIBLE);
            }


        } else {
            gv.setVisibility(View.GONE);
            ll_phone1.setVisibility(View.VISIBLE);
            ll_phone2.setVisibility(View.VISIBLE);
            ll_phone3.setVisibility(View.VISIBLE);
        }


    }

    //没有查询到电话的情况   此时显示默认的
    public void NoShowPhone() {
        gv.setVisibility(View.GONE);
        ll_phone1.setVisibility(View.VISIBLE);
        ll_phone2.setVisibility(View.VISIBLE);
        ll_phone3.setVisibility(View.VISIBLE);
    }

    @Override
    protected boolean isTFragment() {
        return true;
    }

    @Override
    protected String getPageTitle() {
        return TitleToCode.TYPE78.getTitle();
    }


    //判断是否打开了GPS定位
    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }
}
